package com.tian.service.impl;

import com.tian.entity.ChargeSystemMessage;
import com.tian.entity.ChargeSystemMessageContent;
import com.tian.entity.UserCouponExpireTemporary;
import com.tian.mapper.ChargeSystemMessageContentMapper;
import com.tian.mapper.ChargeSystemMessageMapper;
import com.tian.mapper.UserCouponExpireTemporaryMapper;
import com.tian.service.PromptUserCouponExpiredService;
import com.tian.util.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * {@code @description:} 提醒用户优惠券即将过期的服务实现类
 *
 * @author tianwc 公众号：Java后端技术全栈
 * 在线刷题 1200+java面试题和1000+篇技术文章：<a href="https://woaijava.cc/">博客地址</a>
 * {@code @date:} 2024-08-27 21:29
 * {@code @version:} 1.0
 */
@Slf4j
@Service
public class PromptUserCouponExpiredServiceImpl implements PromptUserCouponExpiredService {
    @Resource
    private UserCouponExpireTemporaryMapper userCouponExpireTemporaryMapper;
    @Resource
    private ChargeSystemMessageMapper chargeSystemMessageMapper;
    @Resource
    private ChargeSystemMessageContentMapper chargeSystemMessageContentMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void doPrompt() {
        //具体提醒多久之前的用户优惠券即将过期，这里设置为5天前（可以做一个配置）
        Date expireDate = DateUtils.addDay(new Date(), -5);
        long count = userCouponExpireTemporaryMapper.countByPrompt(expireDate);
        if (count == 0) {
            log.info("没有需要处理的用户优惠券");
            return;
        }
        //批量处理--分批处理
        for (long i = 0; i < count; i += 100) {
            List<UserCouponExpireTemporary> userCouponExpireTemporaries = userCouponExpireTemporaryMapper.selectByExpireDatePage(expireDate, i*100, 100);
            for (UserCouponExpireTemporary userCouponExpireTemporary : userCouponExpireTemporaries) {
                userCouponExpireTemporary.setPrompt(1);
                userCouponExpireTemporaryMapper.updateByPrimaryKey(userCouponExpireTemporary);
                //给用户发站内信---提示用户优惠券即将过期
                ChargeSystemMessageContent chargeSystemMessageContent = chargeSystemMessageContentMapper.selectByPrimaryKey(2);
                ChargeSystemMessage chargeSystemMessage = new ChargeSystemMessage();
                chargeSystemMessage.setMessageId(chargeSystemMessageContent.getId());
                chargeSystemMessage.setUserId(userCouponExpireTemporary.getUserId());
                chargeSystemMessage.setSendTime(new Date());
                chargeSystemMessage.setIsRead(0);
                chargeSystemMessageMapper.insert(chargeSystemMessage);

            }
        }
    }
}
